/***************************************************************************
 *   Copyright (C) 2007-2010 by Lasse Liehu                                *
 *   lliehu@kolumbus.fi                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "logwidget.h"

#include <QTextBrowser>
#include <QVBoxLayout>
#include <QShowEvent>
#include <QCloseEvent>
#include <QSettings>
#include <QDateTime>
#include <QFileDialog>
#include <QMessageBox>
#include <QDir>
#include <QCoreApplication>

LogWidget::LogWidget() : mVerbosityLevel(Normal)
{
    ui.setupUi(this);
    readGeneralSettings();

    //: Window title, %1 = application name
    setWindowTitle(tr("Log - %1").arg(QCoreApplication::applicationName() ));
    setAttribute(Qt::WA_DeleteOnClose, false);

    connect(ui.verbosityLevel_comboBox, SIGNAL(currentIndexChanged(
        const QString&)), this, SLOT(setVerbosityLevel(const QString&)) );
    connect(ui.saveButton, SIGNAL(clicked()), this, SLOT(saveToFile()) );
    connect(ui.settingsButton, SIGNAL(clicked()), this, SLOT(showSettings()) );
    updateVerbosityLevelComboBox();
}

LogWidget::~LogWidget()
{
}

LogWidget::VerbosityLevel LogWidget::verbosityLevel() const
{
    return mVerbosityLevel;
}

void LogWidget::writeToLog(const QString& sysid, const QString& _msg,
    VerbosityLevel vLevel)
{
    if (mVerbosityLevel < vLevel) return;

    QString msg = _msg;
    msg.replace("<", "&lt;");
    msg.replace(">", "&gt;");
    ui.logBrowser->append(QString("<b><font color='blue'>") +
        QDateTime::currentDateTime().toString(Qt::TextDate) + "</font> " +
        sysid + "</b>: " + msg + MessageEndString);
}

void LogWidget::setVerbosityLevel(LogWidget::VerbosityLevel vLevel)
{
    mVerbosityLevel = vLevel;
    QSettings settings(QCoreApplication::organizationName(),
                       QCoreApplication::applicationName() );
    settings.setValue("log_verbositylevel", mVerbosityLevel);
    updateVerbosityLevelComboBox();
}

void LogWidget::showEvent(QShowEvent *evt)
{
    readWindowSettings();
}

void LogWidget::closeEvent(QCloseEvent *evt)
{
    QSettings settings(QCoreApplication::organizationName(),
                       QCoreApplication::applicationName());
    settings.setValue("log_pos", pos() );
    settings.setValue("log_size", size() );
    evt->accept();
}

void LogWidget::setVerbosityLevel(const QString& lvlInStr)
{
    VerbosityLevel lvl = Normal;
    if (lvlInStr == "Normal")
    {
        lvl = Normal;
    }
    else if (lvlInStr == "Debug")
    {
        lvl = Debug;
    }

    setVerbosityLevel(lvl);
}

void LogWidget::updateVerbosityLevelComboBox()
{
    QString curVLevelInStr;
    if (mVerbosityLevel == Normal)
    {
        curVLevelInStr = "Normal";
    }
    else if (mVerbosityLevel == Debug)
    {
        curVLevelInStr = "Debug";
    }
    else
    {
        ui.verbosityLevel_comboBox->setCurrentIndex(0);
        return;
    }

    bool found = false;
    int index = 0;
    for (; index < ui.verbosityLevel_comboBox->count(); ++index)
    {
        if (ui.verbosityLevel_comboBox->itemText(index) == curVLevelInStr)
        {
            found = true;
            break;
        }
    }
    if (found)
    {
        ui.verbosityLevel_comboBox->setCurrentIndex(index);
    }
    else
    {
        ui.verbosityLevel_comboBox->setCurrentIndex(0);
    }
}

void LogWidget::saveToFile()
{
    QString filename = QFileDialog::getSaveFileName(this,
        tr("Save Log To File - %1").arg(QCoreApplication::applicationName()),
        QDir::homePath() + "/NotifierLog.html", tr("HTML Files (*.html *.htm)") );
    if ( ! filename.isEmpty() )
    {
        QFile file(filename);
        if ( ! file.open(QIODevice::WriteOnly | QIODevice::Text) )
        {
            QMessageBox::critical(this, tr("Saving log to file failed", "window title"),
                tr("Saving log to file failed!", "message"));
            return;
        }

        QString html = ui.logBrowser->toHtml();
        html.replace(MessageEndString, "");
        QByteArray dataToWrite = html.toLocal8Bit();
        qint64 bytesWritten = file.write(dataToWrite);
        if (bytesWritten < dataToWrite.size() )
        {
            QMessageBox::critical(this, tr("Saving log to file failed", "window title"),
                tr("Saving log to file failed!", "message"));
        }
        else
        {
            QMessageBox::information(this, tr("Saving log to file succeeded", "window title"),
                tr("Saving log to file succeeded!", "message"));
        }
        file.close();
    }
}

void LogWidget::showSettings()
{
    QMessageBox::information(this, tr("No settings available yet", "window title"),
        tr("There are no settings available yet. When settings are added, "
        "clicking this button will show you them."));
}

void LogWidget::readGeneralSettings()
{
    QSettings settings(QCoreApplication::organizationName(),
        QCoreApplication::applicationName() );
    int vLevel = settings.value("log_verbositylevel", 0).toInt();
    if (vLevel == Normal)
    {
        mVerbosityLevel = Normal;
    }
    else if (vLevel == Debug)
    {
        mVerbosityLevel = Debug;
    }
    else
    {
        mVerbosityLevel = Normal;
    }
}

void LogWidget::readWindowSettings()
{
    QSettings settings(QCoreApplication::organizationName(),
        QCoreApplication::applicationName());
    QPoint pos = settings.value("log_pos", QPoint(0,0)).toPoint();
    QSize size = settings.value("log_size", QSize(400, 200) ).toSize();
    move(pos);
    resize(size);
}

const QString LogWidget::MessageEndString = QString(QChar(0x200b)) +
    QChar(0x200b) + QChar(0x200b);
